﻿using Microsoft.Extensions.Options;
using System;
using System.Data;

namespace Dapper.Core
{
    /// <summary>
    /// 工作单元
    /// </summary>
    public class UnitOfWork : IUnitOfWork
    {
        /// <summary>
        /// 依赖注入 > 获取DBConfig，并设置IDbConnection
        /// </summary>
        /// <param name="option"></param>
        public UnitOfWork(IOptions<DBConfig> option)
        {
            //获取dbConnection对象类型
            var dbConnection = Activator.CreateInstance(
                SqlProvider.GetDbConnectionType(option.Value.DatabaseType),
                new[] { option.Value.ConnectionString }) as IDbConnection;

            //赋值
            _connection = dbConnection;
            _dbType = option.Value.DatabaseType;
        }

        //声明
        DatabaseType _dbType;
        IDbConnection _connection = null;
        IDbTransaction _transaction = null;

        /// <summary>
        /// 数据库类型
        /// </summary>
        DatabaseType IUnitOfWork.DbType
        {
            get { return _dbType; }
        }

        /// <summary>
        /// 数据库连接对象
        /// </summary>
        IDbConnection IUnitOfWork.Connection
        {
            get { return _connection; }
        }

        /// <summary>
        /// 数据库事务对象
        /// </summary>
        IDbTransaction IUnitOfWork.Transaction
        {
            get { return _transaction; }
        }    

        /// <summary>
        /// 开启事务
        /// </summary>
        public void Begin()
        {
            _transaction = _connection.BeginTransaction();
        }

        /// <summary>
        /// 提交事务
        /// </summary>
        public void Commit()
        {
            _transaction.Commit();
            Dispose();
        }

        /// <summary>
        /// 回滚事务
        /// </summary>
        public void Rollback()
        {
            _transaction.Rollback();
            Dispose();
        }

        /// <summary>
        /// 释放事务
        /// </summary>
        public void Dispose()
        {
            if (_transaction != null)
                _transaction.Dispose();
            _transaction = null;
        }
    }
}
